package com.hbnu.tangyalu.jdbc;

import com.hbnu.tangyalu.util.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcDemo07 {
    public static void main(String[] args) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try {
            connection= JdbcUtils.getConnection();
            String sql="select * from tb_user where username like ?";
            preparedStatement =connection.prepareStatement(sql);
            preparedStatement.setString(1,"%i%");
            resultSet=preparedStatement.executeQuery();
            while (resultSet.next()){
                System.out.println(resultSet.getString("username"));
            }
        }
        catch (Exception e){
            throw new RuntimeException(e);
        }
        finally {
//            关闭资源从小到大，一个一个的关闭
            try {
                if (resultSet!=null){
                    resultSet.close();
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }

            try {
                if (preparedStatement!=null){
                    preparedStatement.close();
                }
            }
            catch (SQLException e){
                e.printStackTrace();
            }

            try {
                if (connection!=null){
                    connection.close();
                }
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
}
